package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FileType;
import com.rongke.model.MddVersion;
import com.rongke.service.MddVersionService;
import com.rongke.web.config.ConfigUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.UUID;

/**
 * @MddVersionController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/mddVersion")
@Transactional
@CrossOrigin
public class MddVersionController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private MddVersionService mddVersionService;
    @Autowired
    public ConfigUtil config;
    /**
     * @添加
     * @param mddVersion
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addMddVersion(@RequestBody MddVersion mddVersion){
        log.debug("添加");
        mddVersion.setGmtDatetime(new Date());
        mddVersionService.insert(mddVersion);
        return JsonResp.ok(mddVersion);
    }

    /**
     * @删除
     * @param id 版本id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/deleteVersionOne", method = RequestMethod.GET)
    public JsonResp updateMddVersion(Long id){
        log.debug("删除");
        mddVersionService.deleteById(id);
        return JsonResp.ok("删除成功");
    }
    /**
     * @根据id查找
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/versionList", method = RequestMethod.GET)
    public JsonResp selectMddVersion(){
        log.debug("查找版本列表");
        List<MddVersion> mddVersions = mddVersionService.selectList(null);
        return JsonResp.ok(mddVersions);
    }

    /**
     * @获取当前版本
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findCurrentVersion",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findCurrentVersion(Integer versionType){
        log.debug("获取当前版本");
        EntityWrapper<MddVersion> ew=new EntityWrapper<>();
        ew.eq("status",1);
        ew.eq("version_type",versionType);
        ew.orderBy("gmt_datetime",false);
        List<MddVersion> versions=mddVersionService.selectList(ew);
        if(!versions.isEmpty()){
            return JsonResp.ok(versions.get(0));
        }else {
            return  JsonResp.fa("当前已是最新版本");
        }

    }
    /**
     * @上传当前最新版本
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/upLoadCurrentVersion",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ModelAndView upLoadCurrentVersion(String name, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request){
        log.debug("上传当前最新版本");
        MddVersion version=new MddVersion();
        version.setStatus(1);
        version.setVersionCode(name);
        String versionType=request.getParameter("versionType");
        version.setVersionType(Integer.valueOf(versionType));
        String[] paths = FileType.getPath(FileType.OTHER, 1,request);
        // 获取文件的后缀
        String suffix;
        try {
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        } catch (Exception e) {
            suffix = "";
        }

        String fileName = UUID.randomUUID().toString();
        fileName += suffix;
        String path=paths[0] + File.separator + fileName;
        File saveFile = new File(path);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
        StringBuffer  url=request.getRequestURL().replace(0,4,"https");
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
        String savePath = config.getUploadHost(request, null, saveFile.getParentFile().getName(), saveFile.getName());
        version.setLink(savePath);
        version.setGmtDatetime(new Date());
        mddVersionService.insert(version);
        StringTokenizer st = new StringTokenizer(tempContextUrl,"interface/");
//        String backUrl=tempContextUrl.split("interface/")[0]+"admin/version_list.html";
        String backUrl=st.nextElement()+"admin/version_list.html";
//        String backUrl=basePath+"admin/version_list.html";
        log.debug("返回。。。。"+backUrl);
        System.out.print(backUrl);
        return new ModelAndView("redirect:"+backUrl);
        //return  "redirect:http://127.0.0.1:8020/kbk_admin/version_list.html";
    }

    /**
     * @根据条件查找
     * @param mddVersion
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectMddVersionByCondition(@RequestBody MddVersion mddVersion){
        log.debug("根据条件查找");
        if(mddVersion==null)
            return JsonResp.toFail("参数不能为空");
        List<MddVersion> mddVersionList=mddVersionService.selectByCondition(mddVersion);
        return JsonResp.ok(mddVersionList);
    }




}
